/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import general.util.EntitiesValidation;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import jpa.controller.ObraJpaController;
import jpa.entity.Obra;
import org.primefaces.context.RequestContext;

/**
 *
 * @author isaias
 */
@ManagedBean
@ViewScoped
public class ObraBean {

    private String obraFilterName = null;
    private Obra obra = new Obra();
    private Obra obraSelected = new Obra();
    
    /**
     * Creates a new instance of ObraBean
     */
    public ObraBean() {
    }

    public List<Obra> listObras(){
        return new ObraJpaController().findObraEntitiesByName(obraFilterName);
    }
    
    public void save(){
        List<String> erros = EntitiesValidation.validateObra(obra);
         if(erros.isEmpty()){
            try {
                 new ObraJpaController().create(obra);
                 RequestContext.getCurrentInstance().execute("newObra.hide();");
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                        "Obra criada com sucesso!", null));
                 obra = new Obra();
             } catch (Exception e) {
                 e.printStackTrace();
                  FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "Erro ao tentar criar a obra!", null));
            }
        }else{
            for(String e : erros){
                   FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        e, null));
            }
        }
    }

    public void delete(){
         try {
            obraSelected.setIsDeleted(true);
            new ObraJpaController().edit(obraSelected);
             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                        "Obra removida com sucesso!", null));
        } catch (Exception e) {
            e.printStackTrace();
              FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "Erro ao tentar remover a obra selecionada!", null));
        }


    }

    public Obra getObra() {
        return obra;
    }

    public void setObra(Obra obra) {
        this.obra = obra;
    }

    public String getObraFilterName() {
        return obraFilterName;
    }

    public void setObraFilterName(String obraFilterName) {
        this.obraFilterName = obraFilterName;
    }
    
    public Obra getObraSelected() {
        return obraSelected;
    }

    public void setObraSelected(Obra obraSelected) {
        this.obraSelected = obraSelected;
    }
    
    
}
